<template>
<view>
<view class="container" v-if="pintuanData!=null">
  <view class="product_info">
    <view class="product_left">
      <image class="product_left_img" :src="pintuanData.productBean.imagePath"></image>
      <view class="product_promtion_name" :style="'background:' + setting.platformSetting.defaultColor">
        <text>{{pintuanData.productBean.promotionName}}</text>
      </view>
    </view>
    <view class="product_right">
      <view class="product_name">
        <text>{{pintuanData.productBean.name}}</text>
      </view>
      <view class="product_price">
        <view class="product_tags">
          <text class="product_tags_item" :style="'background:' + setting.platformSetting.defaultColor">包邮</text>
          <text class="product_tags_item" :style="'background:' + setting.platformSetting.defaultColor">拼单省{{pintuanData.productBean.price-pintuanData.productBean.promotionPrice}}元</text><!-- pintuanData.productBean.price-pintuanData.productBean.price*pintuanData.pintuanStrategyBean.priceZhekou -->
        </view>
        <view class="product_pindan_price">
          <text class="product_discount" :style="'color:' + setting.platformSetting.defaultColor">￥{{pintuanData.productBean.promotionPrice||pintuanData.productBean.price}}</text>
          <view class="product_count">
            <text>已拼10万+件</text>
          </view>
        </view>
      </view>
    </view>
  </view>

  <view class="pindan_info">
    <view class="pintuan_user_list">
      <view class="pintuan_user_item" v-for="(pintuanItem, index) in pintuanData.orders" :key="index">
        <view class="pintuan_user_list_tip" :style="'background:' + setting.platformSetting.defaultColor" v-if="index==0"><text>拼主</text></view>
        <image class="user_head_img" :src="pintuanItem.buyerHeadimg"></image>
      </view>
      <view class="unpintuan_user_item" v-for="(item, index) in pintuanData.userCountLimit-pintuanData.attendedUserCount" :key="index">
        <image class="unuser_head_img" src="http://image1.sansancloud.com/jianzhan/2018_9/10/20/2/33_724.jpg"></image>
      </view>
    </view>
    <view class="pintuan_time_num" v-if="pintuanData.recordStatus==1">
      <view class="pintuan_num">仅剩{{pintuanData.userCountLimit-pintuanData.attendedUserCount}}个名额</view>
      <view class="pintuan_time">
        <!-- <time :data="pintuanData.endTime"></time> -->
        <time-component ref='productTimeOne' :receiveData="pintuanData.endTime"></time-component>
        <text style="margin-left:10rpx;">后结束</text>
      </view>
    </view>
    <view class="pintuan_time_num" v-else>
      <view class="pintuan_num">恭喜您拼单成功~</view>
    </view>

    <button class="pintuan_invitation_button" open-type="share" :style="'background:' + setting.platformSetting.defaultColor" v-if="pintuanData.recordStatus==1">
      <text>邀请拼单</text>
    </button>
    <view class="pintuan_invitation_button" :style="'background:' + setting.platformSetting.defaultColor + ';'" v-if="pintuanData.userAddition==0&&pintuanData.recordStatus==1" :data-pintuanid="pintuanData.id" data-way="addPintuan" @tap="readyPay2">
      <text>参加拼单</text>
    </view>
    <view class="pintuan_invitation_button" :style="'border:2rpx solid ' + setting.platformSetting.defaultColor" @tap="toIndex">
      <text :style="'color:' + setting.platformSetting.defaultColor">返回首页</text>
    </view>

    <view class="pinduan_rule">
      <text class="pinduan_rule_title">拼单规则</text>
      <view class="pinduan_rule_list">
        <view class="pinduan_rule_item">
          <text>好友拼单</text>
          <text class="dot">·</text>
        </view>
        <view class="pinduan_rule_item">
          <text>人满发货</text>
        </view>
      </view>
    </view>
  </view>
</view>
<!-- <component is="measure_card2" :setting="showCount" :focusData="productData" :measures="productData.measureTypes" :byNowParams="byNowParams" :measurementJson="measurementJson" :type="bindway"></component> -->
</view>
</template>

<script>

// import time from "../../view/partials/time/time";

export default {
  data() {
    return {
      setting: null,
      // setting 
      pintuanData: null,
      productData: null,
      byNowParams: {
        productId: '',
        itemCount: 1,
        shopId: '',
        cartesianId: '0',
        chatOrder: '',
        fromSource: '',
        orderType: '',
        pintuanCreateType: 0,
        pintuanRecordId: 0
      },
      showCount: false,
      haveMeasuresState: false,
      selectTypeData: "",
      bindway: "",
      measurementJson: {},
      pintuanRecordId: ""
    };
  },

  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('--------product----------', options);
    let that = this;
    that.setData({
      setting: getApp().globalData.setting
    });
    that.setData({
      pintuanRecordId: options.pintuanRecordId
    });

    if (getApp().globalData.loginUser) {
      that.getPintuanDetail();
    } else {
      console.log('======111222333======');
      getApp().globalData.addLoginListener(that);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();

    if (getApp().globalData.loginUser) {
      this.getPintuanDetail();
    } else {
      console.log('======111222333======');
      getApp().globalData.addLoginListener(this);
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
    * 用户点击右上角分享
    */
  onShareAppMessage: function (res) {
    console.log(res);
    let id = this.pintuanData.id;
    let shareName = '拼团活动';
    let shareParams = 'pintuanRecordId=' + id;
    console.log("shareParams", shareParams);
    return getApp().globalData.sharePintuan('pintuan_invitation', shareName, shareParams);
  },
  methods: {
    subNum: function () {
      if (this.byNowParams.itemCount == 1) {
        return;
      }

      this.byNowParams.itemCount--;
      this.setData({
        byNowParams: this.byNowParams
      });
    },
    addNum: function () {
      this.byNowParams.itemCount++;
      this.setData({
        byNowParams: this.byNowParams
      });
    },
    toIndex: function () {
      getApp().globalData.toIndex();
    },
    getPintuanDetail: function () {
      let that = this;
      let getParams = {};
      getParams.pintuanRecordId = that.pintuanRecordId;
      let customIndex = getApp().globalData.AddClientUrl("/get_pintuan_record_detail.html", getParams); // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log('-----------orderDetail--------');
          console.log(res.data);
          let productData = res.data.relateObj.productBean;
          productData.promotionBean = res.data.relateObj.promotionBean;
          productData.promotionBean.pintuanStrategy = res.data.relateObj.pintuanStrategyBean;
          that.setData({
            pintuanData: res.data.relateObj
          });
          that.setData({
            productData: productData
          });
          console.log("===productData===", that.productData);
          wx.hideLoading();
        },
        fail: function (res) {
          that.setData({
            pintuanData: null
          });
          wx.hideLoading();
          getApp().globalData.loadFail();
        },
        complete: function () {
          console.log('=====fail====');
        }
      });
    },
    closeZhezhao: function () {
      this.setData({
        showCount: false
      });
    },

    /* 立即购买 */
    buyNow: function (e) {
      if (!getApp().globalData.checkShopOpenTime()) {
        return;
      }

      if (!getApp().globalData.checkIfLogin()) {
        return;
      }

      let bindway;

      if (e.currentTarget.dataset.way) {
        bindway = e.currentTarget.dataset.way;
      } else {
        bindway = this.bindway;
      }

      console.log('=======bindway======', bindway);

      if (bindway == 'addPintuan') {
        this.setData({
          haveMeasuresState: true
        });
        this.setData({
          selectTypeData: this.selectTypeData
        });
        console.log('-----------addtocart----------');
        this.createOrder22(this.byNowParams);
      }
    },

    /* 创建订单 */
    createOrder22: function (o) {
      var customIndex = getApp().globalData.AddClientUrl("/buy_now.html", o, 'post');
      var that = this; // wx.showLoading({
      //   title: 'loading',
      //   mask: true
      // })

      getApp().globalData.showToastLoading('loading', true);
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log("点击确定后内容", res.data);
          let data = res.data;

          if (!!res.data.orderNo) {
            wx.hideLoading();
            wx.navigateTo({
              url: '/pages/edit_order/index?orderNo=' + res.data.orderNo
            });
          } else {
            wx.hideLoading();
            wx.showToast({
              title: res.data.errMsg,
              image: '/images/icons/tip.png',
              duration: 2000
            });
          }
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        },
        complete: function (res) {}
      });
    },
    readyPay2: function (e) {
      console.log('====e=====', e);

      if (!getApp().globalData.checkIfLogin()) {
        return;
      }

      let way;

      if (e.currentTarget.dataset.way) {
        way = e.currentTarget.dataset.way;
      } else {
        way = e.detail.data.way;
      }

      this.setData({
        bindway: way
      });
      this.setData({
        showCount: true
      });
      this.byNowParams.productId = this.productData.id;
      this.byNowParams.shopId = this.productData.belongShopId;
      this.setData({
        byNowParams: this.byNowParams
      });

      if (way == 'addPintuan') {
        this.byNowParams.pintuanCreateType = 2;
        this.byNowParams.orderType = 0;
        this.byNowParams.pintuanRecordId = this.pintuanData.id;
        this.chooseMeasureItem();
      }
    },

    /* 初始化 选规格 */
    chooseMeasureItem: function (event) {
      console.log('----------初始化规格参数-----------', event);
      let productData = this.productData;

      if (!this.productData.measureTypes) {
        this.productData.measureTypes = [];
        this.setData({
          productData: this.productData
        });
      }

      let focusProduct = productData;
      let selectTypeData = [];

      for (let i = 0; i < focusProduct.measureTypes.length; i++) {
        focusProduct.measureTypes[i].checkedMeasureItem = 0; //初始化选择的数据

        let param = {};
        let selectTypeDataItem = {};
        param.name = focusProduct.measureTypes[i].name;
        param.value = focusProduct.measureTypes[i].productAssignMeasure[0].id;
        selectTypeDataItem.type = focusProduct.measureTypes[i].name;
        selectTypeDataItem.value = focusProduct.measureTypes[i].productAssignMeasure[0].measureName;
        console.log('=====param=====', param);
        this.MeasureParams.push(param);
        selectTypeData.push(selectTypeDataItem);
      }

      this.selectTypeData = selectTypeData;
      console.log('====that.data.selectTypeData======', this.selectTypeData);
      this.setData({
        productData: focusProduct
      });
      console.log('===MeasureParams====', this.MeasureParams);
      this.get_measure_cartesionFun();
    },
    //选择规格小巷的---显示
    radioChange: function (e) {
      let that = this;
      let flag = false;
      console.log("====radioChange=====", e);
      console.log('====that.data.selectTypeData======', that.selectTypeData);

      if (that.selectTypeData) {
        console.log('1111111');

        for (let i = 0; i < that.selectTypeData.length; i++) {
          if (e.currentTarget.dataset.type == that.selectTypeData[i].type) {
            that.selectTypeData.splice(i, 1, e.currentTarget.dataset);
            flag = true;
          }
        }

        if (!flag) {
          that.selectTypeData.splice(that.selectTypeData.length, 1, e.currentTarget.dataset);
          flag = false;
        }
      } else {
        console.log('222222');
        that.selectTypeData = [];
        that.selectTypeData.splice(0, 1, e.currentTarget.dataset);
        that.setData({
          selectTypeData: that.selectTypeData
        });
      }

      console.log('====that.data.selectTypeData======', that.selectTypeData);
      let index = e.currentTarget.dataset.index;
      let indexJson = getApp().globalData.getSpaceStr(index, '-');
      console.log("-----", indexJson);
      let focusItem = that.productData;
      focusItem.measureTypes[indexJson.str1].checkedMeasureItem = indexJson.str2;
      that.setData({
        productData: focusItem
      });
    },
    //选择规格小巷---获取数据
    chooseMeasure: function (e) {
      console.log(e.detail.value);
      let chooseMeasureJson = getApp().globalData.getSpaceStr(e.detail.value, '-');
      console.log(chooseMeasureJson);

      for (let i = 0; i < this.MeasureParams.length; i++) {
        if (this.MeasureParams[i].name == chooseMeasureJson.str1) {
          this.MeasureParams[i].value = chooseMeasureJson.str2;
        }
      }

      this.get_measure_cartesionFun();
    },
    //获取规格价格参数
    get_measure_cartesionFun: function () {
      this.setData({
        measurementJson: {
          waitDataState: false
        }
      });
      let productId = this.productData.id;
      let postStr = '';

      if (this.MeasureParams.length == 0) {
        this.byNowParams.cartesianId = '0';
        this.setData({
          measurementJson: {
            waitDataState: true
          }
        }); //没有规格时 不需要等待请求

        return;
      }

      for (let i = 0; i < this.MeasureParams.length; i++) {
        postStr += this.MeasureParams[i].value + ',';
      }

      let param = {};
      param.productId = productId;
      param.measureIds = postStr;
      console.log(postStr);
      let customIndex = getApp().globalData.AddClientUrl("/get_measure_cartesion.html", param);
      var that = this;
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log(res.data);
          that.byNowParams.cartesianId = res.data.id;
          that.setData({
            measurementJson: res.data
          });
          that.measurementJson.waitDataState = true;
          that.setData({
            measurementJson: that.measurementJson
          });
          that.byNowParams.itemCount = that.measurementJson.minSaleCount;
          that.setData({
            byNowParams: that.byNowParams
          });
        },
        fail: function (res) {
          console.log("fail");
          getApp().globalData.loadFail();
        },
        complete: function () {}
      });
    },
    loginSuccess: function (user) {
      console.log("pre apply mendian login success call back!", user);
      this.getPintuanDetail();
    },
    loginFailed: function (err) {
      console.log("login failed!!");
      wx.showToast({
        title: '登录失败',
        image: '/images/icons/tip.png',
        duration: 2000
      });
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>